package controllers

/**
	测试Controller
 */
import (
	"go_backend/models"
	"github.com/astaxie/beego"
)

type YyuserController struct {
	beego.Controller
}

// @Title Get
// @Description get all the data
// @router /demo/all [GET]
func (this *YyuserController) Get() {
	datas := models.QueryUserAll()
	this.resJson("ok~", datas)
}

// @Title GetOne
// @Description find one the record
// @router /demo/one/:id [GET]
func (this *YyuserController) GetOne() {
	id, err := this.GetInt(":id")
	if err != nil {
		this.resJson("faild", "")
		return
	}
	datas, bool := models.QueryUserById(id)
	this.ifBool(bool, "bool为false!", datas)
}

// @Title Store
// @author  liqi 2018/12/12 13:58
// @Description create new record
// @Param   uid string  true    "The uid you want to delete"
// @router /demo/store [POST]
func (this *YyuserController) Store() {
	user := models.YyUser{}
	if err := this.ParseForm(&user); err != nil {
		this.resJson("出错了", "")
	}
	id, bool := models.CreateUser(user)
	this.ifBool(bool, "create failed!", id)
}

// @Title Update
// @author  liqi 2018/12/12 15:34
// @Description	update one record
// @router /demo/update/:id	[PUT]
func (this *YyuserController) Update() {
	id, err := this.GetInt(":id")
	this.errIsNil(err)
	user := models.YyUser{}
	if err := this.ParseForm(&user); err != nil {
		this.resJson("出错了", "")
	}
	bool := models.UpdateUserById(id, user)
	this.ifBool(bool, "change failed!", "")
}

// @Title DeleteUser
// @author  liqi 2018/12/12 16:08
// @Description	delete one record
// @router /demo/del/:id [DELETE]
func (this *YyuserController) DeleteUser() {
	id, err := this.GetInt(":id")
	this.errIsNil(err)
	bool := models.DeleteUserById(id)
	this.ifBool(bool, "delete failed!", "")
}

// @Title   ifBool
// @author  liqi 2018/12/12 16:20
// @Description	judge bool , true or false
func (this *YyuserController) ifBool(bool bool, errmsg string, data interface{}) {
	if !bool {
		this.resJson(errmsg, "")
	}
	this.resJson("ok~", data)
}

// @Title errIsNil
// @Description judge error
func (this *YyuserController) errIsNil(err error) {
	if err != nil {
		this.resJson("error is nil!", "")
		return
	}
}

// @Title resJson
// @Description global response
func (this *YyuserController) resJson(msg string, data interface{}) {
	this.Data["json"] = map[string]interface{}{"code": 200, "message": msg, "data": data}
	this.ServeJSON()
}
